44% completed
Here is the step-by-step system design for a Stock Exchange.
1. Problem Definition and Scope
We are designing a centralized Stock Exchange where retail and institutional traders can buy and sell shares of public companies.
The core goal is to match buy and sell orders with strict fairness (First-In-First-Out) and extremely low latency.
- Main User Groups:
-
Traders: Retail users (apps) and Institutional algorithms (bots) placing orders.
-
Market Data Consumers: Users or systems watching real-time price feeds.
-
Admins: Staff monitoring market health and trade halts.
-
- Scope:
-
In Scope: The Matching Engine (core logic), Order Management (validation/risk), and Market Data Distribution.
-
Out of Scope: User registration (KYC), fiat payments (banking integration), and post-trade clearing and settlement (the T+2 legal transfer of assets).
-
2. Clarify functional requirements
Must Have:
-
Place Limit Order: Buy/Sell a specific quantity at a specific price.
-
Place Market Order: Buy/Sell immediately at the best available price.
-
Cancel Order: Cancel an open order if it has not been filled.
-
Order Matching: Automatically match orders based on Price-Time Priority (Best price wins; if prices are equal, earliest order wins).
-
Real-time Order Book: Users can view the current "depth of market" (list of open bids and asks).
-
Trade History: Users receive immediate confirmation when a trade executes.
Nice to Have:
-
Stop-loss orders.
-
Historical candlestick (OHLC) charts.
3. Clarify non-functional requirements
-
Latency: Critical. The internal matching engine must process an order in microseconds (< 1ms). End-to-end latency (click to ack) should be < 50ms.
-
Throughput: High write load. Target 100,000 orders per second (TPS) peak to handle market open/close bursts.
-
Consistency: Strong Consistency. We cannot double-sell a stock or overspend a user's balance. The system must be deterministic.
-
Availability: High (99.99%) during market hours.
-
Fairness: Strict FIFO ordering is required.
-
Durability: Zero data loss. Every accepted order must be persisted.
4. Back of the envelope estimates
- Traffic Math:
-
Assumption: 1 Million Daily Active Users (DAU).
-
Orders: Average 10 orders/user/day (mix of humans and bots) = 10 Million orders/day.
-
Trading Window: ~6.5 hours (≈ 23,400 seconds).
-
Average QPS:
QPS. -
Peak QPS: Markets are extremely bursty. Peak can be 100x average.
-
Design Goal: 100,000 QPS write capacity.
-
- Storage:
-
Order object: ~200 bytes.
-
Daily storage: 10M orders * 200 bytes
2 GB/day. -
Yearly storage: 2 GB * 250 trading days
500 GB. -
Conclusion: Storage volume is low; the challenge is CPU speed and I/O latency, not disk space.
-
- Bandwidth (Market Data):
- This is the bottleneck. If 100k active users subscribe to a live feed (10 updates/sec, 1KB each):
- 100,000 * 10 * 1 * KB = 1 GB/s outbound traffic. We need an efficient fan-out strategy.
5. API design
We use REST for order placement (simplicity) and WebSockets for the return path (execution reports and market data).
1. Place Order
- Method: POST /v1/orders
- Request:
{
"symbol": "AAPL",
"side": "BUY",
"type": "LIMIT",
"price": 150.25,
"quantity": 100
}
- Response: 202 Accepted { "order_id": "1005", "status": "PENDING" }
- Note: Returns 202 because the actual matching happens asynchronously.
2. Cancel Order
- Method: DELETE /v1/orders/{order_id}
- Response: 202 Accepted
3. Get Order Book (Snapshot)
- Method: GET /v1/market/depth/{symbol}?level=10
- Response:
{
"symbol": "AAPL",
"bids": \[\[150.25, 100\], \[150.20, 250\]\],
"asks": \[\[150.30, 50\], \[150.35, 100\]\]
}
4. Real-time Stream (WebSocket)
- Endpoint: wss://api.exchange.com/stream
- Subscribe: { "topic": "market:AAPL" }
- Event: { "type": "trade", "price": 150.25, "qty": 10, "timestamp": 1678886000 }
6. High level architecture
Standard database-centric architectures are too slow for a matching engine because of locking overhead. We will use an In-Memory Matching Engine with a Sequencer to ensure determinism.
Component Roles:
-
API Gateway: Handles authentication, rate limiting, and basic request validation.
-
Risk Engine (Order Manager): Critical Component. Checks if the user has enough cash (for buy) or stock (for sell) before the order enters the system. It locks these funds in a high-speed cache (Redis) to prevent double-spending.
-
Sequencer: A high-throughput log (e.g., Kafka). It assigns a strictly increasing Sequence ID to every order. This guarantees that if the system crashes, we can replay events in the exact same order to restore state.
-
Matching Engine: The core logic. Keeps the Order Book in RAM. Single-threaded per stock symbol to avoid locking contention.
-
Message Bus: The engine publishes results ("Trade Executed", "Order Cancelled") here.
-
DB Workers: Async processes that read from the bus and persist trades to the SQL database.
-
Market Data Service: Reads from the bus and pushes real-time updates to WebSocket gateways.
7. Data model
We use a hybrid model: In-Memory for execution speed, and Relational SQL for the system of record.
A. In-Memory (Inside Matching Engine)
-
Structure: Map<Symbol, OrderBook>
-
Inside OrderBook: Two Sorted Trees (e.g., Red-Black Tree).
- Bids (Buy): Max-Heap property (Highest price first).
- Asks (Sell): Min-Heap property (Lowest price first).
- Order List: Each node in the tree contains a Linked List of orders to support FIFO (Time priority) for orders at the exact same price.
B. Database (PostgreSQL)
- Users: user_id, email, kyc_status.
- Wallets: user_id, currency, balance, locked_amount.
- Note: Use DECIMAL type for money, never FLOAT.
- Orders: id, user_id, symbol, side, type, price, status (OPEN/FILLED/CANCELLED).
- Trades: id, buy_order_id, sell_order_id, price, quantity, executed_at.
8. Core flows end to end
To achieve microsecond latency, we cannot use a standard web architecture where the application waits for a database write. Instead, we divide the system into two distinct pipelines:
- The Hot Path (Synchronous): Ingestion, Risk Validation, and Sequencing.
- The Cold Path (Asynchronous): Matching, Persistence, and Notification.
We will trace the "Life of an Order" through these phases, plus the critical "Cancellation" edge case.
Phase 1: Ingestion (The Hot Path)
Goal: Validate the order and accept it as fast as possible. No heavy processing or DB writes occur here.
Scenario: User "Alice" wants to buy 10 shares of AAPL at $150.
- Request Arrival:
- Alice’s client sends
POST /orders{symbol: "AAPL", side: "BUY", price: 150, qty: 10}. - The API Gateway authenticates the user (JWT) and performs basic rate limiting.
- Risk Engine Validation (Pre-Trade Checks):
-
Before the order reaches the matching engine, we must ensure Alice can afford it.
-
The Risk Engine checks Alice's balance in the Redis Cache (not the SQL DB, which is too slow).
-
Calculation: Cost =
1,500. -
Logic: Does Alice have $1,500 available?
-
Locking: If yes, the Risk Engine atomically freezes $1,500 in Redis. This prevents her from spending this same money on another order while this one is in flight.
-
Failure: If funds are insufficient, return HTTP 400 immediately.
- Sequencing (The Point of No Return):
-
Once validated, the order is wrapped in an event object and pushed to the Sequencer (Kafka).
-
Crucial Step: The Sequencer assigns a global ID (e.g.,
Sequence #1005). -
Why? This ensures determinism. If the system crashes, we can replay events from the Sequencer in the exact same order to restore the exact same state.
- Client Response:
-
The API returns
HTTP 202 Acceptedwithorder_id: 1005. -
Note: We do not return "Trade Executed" yet. The client knows the order is safely in the system, but it hasn't matched yet.
Phase 2: The Matching Engine (The Core Logic)
Goal: Deterministic, single-threaded execution in Memory.
The Matching Engine is a loop that consumes messages from the Sequencer one by one. It holds the Order Book in RAM (typically using Red-Black Trees).
- Ingest Event #1005:
- The Engine reads "Buy 10 AAPL @ $150" from the Sequencer.
- Attempt Match (Crossing the Spread):
-
The Engine looks at the Asks (Sell) Tree for AAPL.
-
Logic: Is there a Sell order with
price$150? -
Outcome A: The "Maker" (No Match)
-
If the cheapest seller is asking $151, no trade happens.
-
Alice's order is added to the Bids (Buy) Tree at the $150 node.
-
Event Emitted:
OrderAcknowledged(Status: OPEN). -
Result: Alice provides liquidity to the market.
-
Outcome B: The "Taker" (Immediate Match)
-
Suppose "Bob" has a sell order waiting at $149.
-
Since
149 (Bob), a trade occurs! -
Price Logic: The trade executes at the resting price (
1 savings per share). -
Execution:
-
Bob's order is removed from the book.
-
Alice's order is filled immediately and never enters the book.
-
Event Emitted:
TradeExecuted -
{ Buyer: Alice, Seller: Bob, Price: $149, Qty: 10 }
- Output:
- The Engine publishes the resulting event to the Message Bus (e.g., a "Results" Kafka topic).
- Note: The Engine does not write to the SQL database. It only emits events to keep latency low (< 1ms).
Phase 3: Post-Trade Settlement (The Cold Path)
Goal: Durability, Reporting, and Data Fan-out.
Multiple workers read from the "Results" topic independently. This decouples user notification from database writing.
- Persistence Worker (The SQL Writer):
- Reads
TradeExecuted. - SQL Transaction:
- Insert row into
Tradestable. - Update Alice and Bob's rows in
Orderstable toFILLED. - Money Movement:
- Debit $1,490 (actual cost) from Alice's locked balance.
- Credit $1,490 to Bob's cash balance.
- Refund: Since Alice locked
1,490, release the remaining $10 back to her available balance.
- Notification Service (WebSockets):
- Reads
TradeExecuted. - Finds Alice’s active WebSocket connection.
- Pushes:
{"type": "ORDER_FILLED", "symbol": "AAPL", "price": 149, "qty": 10}. - Alice’s app UI updates instantly (Total time from click to notification: ~20-50ms).
- Market Data Service (Public Feed):
- Reads
TradeExecuted. - Updates the "Last Traded Price" (LTP) and Candlestick charts.
- Broadcasts the new price ($149) to all users subscribing to the
market:AAPLstream.
Edge Case: Cancellation
What happens if Alice wants to cancel her order?
- Request: Alice sends
DELETE /orders/1005. - Sequencing: The request is assigned
Sequence #1020. - Race Condition Handling:
- The Matching Engine reads event #1020.
- It checks if Order #1005 is still in the RAM Order Book.
- If Yes: Remove it. Emit
OrderCancelled. - If No: This means the order was already filled (e.g., at Sequence #1010). The Engine emits
CancelRejected. - Why this matters: We never check the Database status for cancellation; the in-memory engine is the single source of truth.
9. Caching and read performance
The Matching Engine is write-sensitive. We isolate it from read traffic.
- Order Book Replication:
- The Matching Engine does not answer API requests.
- Instead, it acts as a "Publisher." It pushes a snapshot of the book (top 50 levels) every 50ms to Redis.
- The REST API (GET /depth) reads purely from Redis.
- User Data:
- User profiles and wallet balances are cached in Redis to speed up the pre-trade Risk Check.
- Static Data:
- Ticker symbols, company names, and logos are served via CDN.
10. Storage, indexing and media
- Primary Data (SQL):
- We use PostgreSQL for ACID compliance.
- Partitioning: The Trades table grows indefinitely. We partition it by Date (e.g., trades_2024_01).
- Write-Ahead Log (WAL):
- The Sequencer (Kafka) acts as the recovery log. We retain messages for 3-7 days.
- If the Matching Engine crashes, we restart it and replay the Kafka topic to rebuild the in-memory trees.
- Archival:
- Trades older than 1 year are moved to Object Storage (S3) in Parquet format for analytics and regulatory audits.
11. Scaling strategies
The Matching Engine is the bottleneck because matching for a single symbol must be serial (single-threaded) to ensure strict ordering.
- Sharding by Symbol:
- We split the universe of symbols.
- Shard 1: Handles A-M (AAPL, GOOG...).
- Shard 2: Handles N-Z (NFLX, TSLA...).
- The Risk Engine hashes the symbol and routes the order to the correct Sequencer partition.
- Handling "Hot" Symbols:
- If one symbol (e.g., GME) exceeds the capacity of a single CPU core (approx 50k-100k TPS), we must optimize code (C++/Rust) or use hardware acceleration (FPGA). We cannot horizontal scale a single order book easily.
- Read Scaling:
- The Market Data Service and WebSocket servers are stateless. We can autoscale them to hundreds of instances to handle millions of concurrent connections.
12. Reliability, failure handling and backpressure
- Active-Passive HA:
- For each Shard, we run two instances of the Matching Engine: Primary and Standby.
- Primary: Reads from Sequencer, updates RAM, emits trades.
- Standby: Reads from Sequencer, updates RAM, but does not emit trades (Hot Standby).
- Failover: If Primary stops heartbeating, Standby takes over instantly. Since it processed the same inputs from the Sequencer, its state is guaranteed to be correct.
- Backpressure:
- If the Matching Engine falls behind the Sequencer (lag increases), the Risk Engine must start rejecting new orders (HTTP 503) to prevent a "death spiral."
- Idempotency:
- Every order has a unique UUID. The engine ignores duplicates to prevent processing the same order twice during network retries.
13. Security, privacy and abuse
- Network Isolation: The Matching Engine runs in a private subnet. Only the Risk Engine/Gateway can reach it.
- Audit Trails: The Sequencer log is immutable. It provides a cryptographic proof of exactly what order requests arrived and in what order, preventing insider manipulation.
- DDoS Protection: Rate limiting is enforced per API Key (e.g., 50 req/sec). High-frequency trading firms use separate, secure connections (VPNs/Cross-connects).
- Encryption: All data in transit is TLS 1.3 encrypted. Sensitive wallet data is encrypted at rest.
14. Bottlenecks and next steps
- Bottleneck: Single-Threaded CPU speed.
- Next Step: Use the LMAX Disruptor pattern (ring buffer) instead of standard queues to reduce locking overhead and cache misses, achieving millions of TPS on a single thread.
- Bottleneck: GC Pauses (if using Java/Go).
- Next Step: Rewrite the core engine in Rust or C++ for manual memory management and predictable latency.
- Bottleneck: Fan-out to millions.
- Next Step: Use a tree of relay servers or specialized real-time infrastructure (like IP Multicast for institutional clients) to reduce network load.
Summary:
-
Architecture: Centralized In-Memory Matching Engine for microsecond latency.
-
Reliability: Sequencer ensures deterministic replay and consistency.
-
Scaling: Shard by Stock Symbol.
-
Trade-off: We prioritize Consistency and Latency over complex features, accepting that the system must handle backpressure by rejecting orders if overloaded.
On this page
1. Problem Definition and Scope
2. Clarify functional requirements
3. Clarify non-functional requirements
4. Back of the envelope estimates
5. API design
6. High level architecture
7. Data model
8. Core flows end to end
Phase 1: Ingestion (The Hot Path)
Phase 2: The Matching Engine (The Core Logic)
Phase 3: Post-Trade Settlement (The Cold Path)
Edge Case: Cancellation
9. Caching and read performance
10. Storage, indexing and media
11. Scaling strategies
12. Reliability, failure handling and backpressure
13. Security, privacy and abuse
14. Bottlenecks and next steps